<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */


/**
 * Smarty truncate modifier plugin
 *
 * Type:     modifier<br>
 * Name:     truncate<br>
 * Purpose:  Truncate a string to a certain length if necessary,
 *           optionally splitting in the middle of a word, and
 *           appending the $etc string or inserting $etc into the middle.
 * @link http://smarty.php.net/manual/en/language.modifier.truncate.php
 *          truncate (Smarty online manual)
 * @author   Monte Ohrt <monte at ohrt dot com>
 * @param string
 * @param integer
 * @param string
 * @param boolean
 * @param boolean
 * @return string
 */


/**
 * 截取字符串（能处理中文）
 * @param $str
 * @param $start
 * @param $cut_length
 * @param $encoding
 * @return unknown_type
 */
function smarty_modifier_cut_str($str, $start, $cut_length, $encoding = 'utf-8') {
	$length = mb_strlen ( $str, $encoding );
	$real_length = $cut_length;
	if ($length > $cut_length) {
		$real_length = 0;
		$cut_length += $cut_length;
		for($i = 0; $i < $length; $i ++) {
			if ($cut_length <= 0){
				break;
			}
			$char = mb_substr ( $str, $i, 1, $encoding );
			if (is_chinese_char ( $char )) {		
				$cut_length  = $cut_length - 2;
				$real_length++;
			} else {
				$cut_length--;
				$real_length++;
			}
		}
	} 
//	echo("$real_length ###");
	
	return mb_substr ( $str, $start, $real_length, $encoding );
}

/* vim: set expandtab: */

?>
